
<template>
  <div style="background:#ffffff; padding:20px" >
    <a-form
      id="components-form-demo-validate-other"
      :form="form"
      v-bind="formItemLayout"
      @submit="handleSubmit"
    >
      <a-form-item
        label="销售模式">
        <a-radio-group v-model="value1" :options="plainOptions" @change="onChange" />
      </a-form-item>
      <a-form-item
        label="企业类型">
        <a-radio-group v-model="value2" :options="typeOptions"   />
      </a-form-item>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="12" :md="12" :sm="12">
            <a-form-item
              label="企业名称"
              :labelCol="{lg: {span: 12}, sm: {span: 12}}"
              :wrapperCol="{lg: {span: 12}, sm: {span: 12} }">
              <a-input placeholder="请输入企业名称" v-model="enterprise.enterpriseName" />
            </a-form-item>
        </a-col>
        <a-col :lg="12" :md="12" :sm="12">
          <a-form-item
            label="所属企业"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 12}, sm: {span: 12} }"
            >
            <a-select
              show-search
              placeholder="请选择一个企业"
              option-filter-prop="children"
              :filter-option="filterOption"
              v-model="enterprise.parentId"
              @change="handleChange"
            >
              <a-select-option  v-for="(item,index) in enterpriseAddr" :key="index" :value="item.id">
                {{item.enterprise_name}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="12" :md="12" :sm="12">
        <a-form-item
          label="统一社会信用代码"
          :labelCol="{lg: {span: 12}, sm: {span: 12}}"
          :wrapperCol="{lg: {span: 12}, sm: {span: 12} }">
          <a-input :min="0" :max="500" placeholder="请输入统一社会信用代码" v-model="enterprise.enterpriseUscc" />
        </a-form-item>
        </a-col>
        <a-col :lg="8" :md="8" :sm="8">
        <a-button @click="query">
            查询
          </a-button>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="12" :md="12" :sm="12">
          <a-form-item
            label="负责人姓名"
            :labelCol="{lg: {span: 12}, sm: {span: 12}}"
            :wrapperCol="{lg: {span: 12}, sm: {span: 12} }"
          >
            <a-input :min="0" :max="500" placeholder="请输入负责人姓名" v-model="enterprise.contactPerson"  />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="12" :sm="12">
          <a-form-item
            label="负责人手机"
            :labelCol="{lg: {span: 4}, sm: {span: 12}}"
            :wrapperCol="{lg: {span: 12}, sm: {span: 12} }">
            <a-input :min="0" :max="500" placeholder="请输入负责人手机" v-model="enterprise.contactPhone" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16">
        <a-col :lg="12" :md="14" :sm="12">
           <a-form-item
             label="注册地址"
             :labelCol="{lg: {span: 12}, sm: {span: 12}}"
             :wrapperCol="{lg: {span: 12}, sm: {span: 12} }">
        <a-input placeholder="请输入注册地址" v-model="enterprise.registerAddr" />
      </a-form-item>
        </a-col>
        <a-col :lg="12" :md="12" :sm="12">
        <a-form-item
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 12}, sm: {span: 12} }"
          label="所在区域">
        <a-select
          style="width: 100%"
          v-model="enterprise.registerDistinct"
          placeholder="请选择所在区域"
        >
          <a-select-option v-for="item in qy" :key="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
        </a-col>
      </a-row>
<!--      <a-form-item  label="代理品牌" >-->
<!--        <j-tree-select-->
<!--          v-decorator="[ 'brandIds', {}]"-->
<!--          placeholder="请选择品牌"-->
<!--          dict="cxm_brand,brand,id"-->
<!--          pidField="parent_id"-->
<!--          pidValue=""-->
<!--          multiple>-->
<!--        </j-tree-select>-->
<!--      </a-form-item>-->
      <a-row class="form-row" :gutter="16">
        <a-col :lg="12" :md="14" :sm="12">
          <a-form-item
            label="其他品牌"
            :labelCol="{lg: {span: 12}, sm: {span: 14}}"
            :wrapperCol="{lg: {span: 12}, sm: {span: 12} }">
            <a-input placeholder="请输入其他品牌用,间隔" v-model="enterprise.brandOth" />
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="14" :sm="12">
          <a-form-item
            label="代理品牌个数"
            :labelCol="{lg: {span: 4}, sm: {span: 8}}"
            :wrapperCol="{lg: {span: 8}, sm: {span: 8} }">
            <a-input-number
              :min="0"
              :max="99"
              v-model="enterprise.brandNbr"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item
        label="营业执照扫描件">
        <j-upload v-model="enterprise.usccScancopy"></j-upload>
      </a-form-item>
      <a-form-item  label="经营地址">
        <a-form-model
          ref="dynamicValidateForm"
          :model="dynamicValidateForm"
          v-bind="formItemLayoutWithOutLabel"
        >
          <a-row>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item
            v-for="(domain, index) in dynamicValidateForm.domains"
            :key="domain.key"
          >
            <a-input
              setFieldsValue="domain.value"
              placeholder="请输入经营地址"
              style="width: 60%; margin-right: 8px"
            />
            <a-icon
              v-if="dynamicValidateForm.domains.length > 1"
              class="dynamic-delete-button"
              type="minus-circle-o"
              :disabled="dynamicValidateForm.domains.length === 1"
              @click="removeDomain(domain)"
            />
          </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
              <a-form-model-item v-bind="formItemLayoutWithOutLabel">
            <a-button type="dashed" style="width: 40%" @click="addDomain">
              <a-icon type="plus" /> 添加
            </a-button>
          </a-form-model-item>
          </a-col>
          </a-row>
        </a-form-model>

      </a-form-item>
<!--	    <a-form-item style="height:600px;"-->
<!--        label="品牌选择">-->
<!--        <dataLevelRef v-model="brands" v-decorator="['brands', {}]"></dataLevelRef>-->
<!--      </a-form-item>-->

      <a-form-item
        label="代理品牌">
        <a-input placeholder="请输入代理品牌" :disabled=true v-model="enterprise.brands"  />
        <a-button type="primary" @click="getInfo()">
          选择品牌
        </a-button>
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
        <a-button type="primary" html-type="submit">
          提交
        </a-button>
      </a-form-item>
    </a-form>
    <data-level-ref ref="DataLevelRef"  v-on:closeMain="closeMain"></data-level-ref>
  </div>
</template>

<script>
import { cxmEnterpriseList,cxmEnterpriseAdd,queryEnterprise } from '@api/api'
import JTreeSelect from '@/components/jeecg/JTreeSelect'
import pick from 'lodash.pick'
import moment from "moment"
import JUpload from '@/components/jeecg/JUpload'
import { getAction, httpAction, postAction, putAction} from '@api/manage'
import { USER_INFO } from '@/store/mutation-types'
import Vue from 'vue'
import DataLevelRef from '@/components/jeecg/DataLevelRef'

const plainOptions = [
  { label: '代理', value: '0' },
  { label: '直销', value: '1' },
];
const typeOptions = [
  { label: '集团', value: '0' ,disabled: 'disabled'},
  { label: '企业', value: '1' ,disabled: 'disabled' },
  { label: '厂商', value: '2' ,disabled: 'disabled' },
];
export default {
  name: "CxmEnterpriseModal",
  components: {
    JTreeSelect,
    JUpload,
    DataLevelRef
  },
  data: () => ({
    formItemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    },
    formData: {
      areaLinkage2: '140221',
      sex: 1
    },
    formItemLayoutWithOutLabel: {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    },
    dynamicValidateForm: {
      domains: [],
    },
    dynamicValidate:[],
    plainOptions,
    typeOptions,
    brands:'',
    cities:'',
    secondCity:'',
    value1:'',
    value2:'',
    disabled: true,
    model: {},
    enterprise:{
      
    },
    enterpriseAddr:[],
    qy:[
      '黄浦区'
      ,'卢湾区'
      ,'徐汇区'
      ,'长宁区'
      ,'静安区'
      ,'普陀区'
      ,'闸北区'
      ,'虹口区'
      ,'杨浦区'
      ,'宝山区'
      ,'闵行区'
      ,'嘉定区'
      ,'浦东新区'
      ,'松江区'
      ,'金山区'
      ,'青浦区'
      ,'南汇区'
      ,'奉贤区'
      ,'崇明区'
    ],
    url: {
      list: "/cxm/cxmEnterprise/list",
      add: "/cxm/cxmEnterprise/add",
    }
  }),
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'validate_other' });
  },
  created () {
    console.log("获取企业信息并赋值上去")
    let userinfo = Vue.ls.get(USER_INFO);
    console.log(userinfo)
    this.addDomain();
    // let httpurl = '/sys/permission/getUserPermissionByToken';

    // getAction(httpurl, {token: token}).then((res)=>{
    //   console.log(res)
    //   if(res.success){
    //
    //   }else{
    //     that.$message.warning(res.message);
    //   }
    // })
    // this.model = {
    //   'enterpriseName':'123123'
    // }
    // this.$nextTick(() => {
    //   this.form.setFieldsValue(pick(this.model
    //     ,'enterpriseName'))
    //   //时间格式化
    // });
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      const that = this;
      var str='';
      for(var a=0;a<that.dynamicValidateForm.length;a++){
        if(a==that.dynamicValidateForm.length-1){
          str+=that.dynamicValidateForm.domains.value.toString();
        }else{
          str+=that.dynamicValidateForm.domains.value.toString()+",";

        }
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          this.enterprise.manageType =  this.value1;
          this.enterprise.enterpriseType = this.value2;
          this.enterprise.operationAddr = str;
          let formData = this.enterprise;
          //匹配品牌个数
          var i=0;
          if(this.enterprise.brands!=null&&this.enterprise.brandOth!=null){
           i = this.enterprise.brands.split(",").length + this.enterprise.brandOth.split(",").length;
          }else if(this.enterprise.brands!=null){
            i = this.enterprise.brands.split(",").length
          }else if(this.enterprise.brandOth!=null){
            i = this.enterprise.brandOth.split(",").length
          }
          if(i!=this.enterprise.brandNbr&&i!=0){
            this.$message.error("选择品牌数不匹配")
            return ;
          }
          httpAction(this.url.add, formData, 'post').then((res) => {

            if (res.success) {
              this.updateUser();
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }

          })
          // cxmEnterpriseAdd(CxmEnterprise).then((res)=>{
          //   if(res.success){
          //     that.$message.success(res.message);
          //     let params= {
          //       uscc :CxmEnterprise.enterpriseUscc
          //     }
          //   }else{
          //     that.$message.warning(res.message);
          //   }
          // })
        }
      });
    },
    normFile(e) {
      console.log('Upload event:', e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    onChange(e) {
      if(this.value1 == '0') {
        this.value2 = ''
        this.typeOptions[0].disabled = !this.disabled;
        this.typeOptions[1].disabled = !this.disabled;
        this.typeOptions[2].disabled = this.disabled;
      }else {
        this.value2 = ''
        this.typeOptions[0].disabled = this.disabled;
        this.typeOptions[1].disabled = this.disabled;
        this.typeOptions[2].disabled = !this.disabled;
      }
    },
    onChange2(e) {
      if(this.value2 == 1) {
        cxmEnterpriseList().then((res)=>{
          if(res.success){
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i];
              this.enterpriseAddr.push(temp);
            }
            console.log(this.enterprise)
            console.log("企业数据查询")
          }
        })
      }else{
        this.enterpriseAddr= [];
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    handleChange(value) {
      this.brandsinfo = this.enterpriseAddr[value]
    },
    query(){
      const that = this;
      this.form.validateFields((err, values) => {
        let params = {
          enterpriseUscc : this.enterprise.enterpriseUscc
        };
        if(this.enterprise.enterpriseUscc!=null&&this.enterprise.enterpriseUscc!=''){
          queryEnterprise(params).then((res)=>{
            if(res.success){
              console.log(res)
              that.$message.success(res.message);
              this.enterprise = res.result
              // this.$nextTick(() => {
              //   this.form.setFieldsValue(pick(this.model,'enterpriseName','enterpeiseShort','parent_id','enterpriseUscc','usccScancopy','enterpriseCode','contactPerson'
              //     ,'contactPhone','enterpriseType','manageType','brandIds','brands','brandOth','brandNbr','brandChk','registerAddr','registerDistinct' ,'operationAddr'
              //     ,'isApproved','isSeparate','loginname','passcode','logintoken','createTime','createUser','updateTime','updateUser'))
              //   //时间格式化
              // });
            }else{
              that.$message.warning(res.message);
            }
          })
        }else{
          that.$message.warning("请输入企业信用代码");
        }
      })
    },
    removeDomain(item) {
      let index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: '',
        key: Date.now(),
      });
    },
    //弹出组件
    getInfo() {
      this.$refs.DataLevelRef.showDrawer();
    },
    //获取子组件传输方法
    closeMain(val){
      let brandIds = val;
      console.log(val)
      this.enterprise.brandIds = val.brandIds
      this.enterprise.brands = val.brands
    },
    updateUser(){
      let params={
        uscc:this.enterprise.enterpriseUscc,
        name:this.enterprise.enterpriseName
      }
      putAction("/sys/user/updateUserUscc", params).then((res) => {
        if (res.success) {
          console.log("企业报备成功")
        }
      });
    }
  },
};
</script>
<style>
#components-form-demo-validate-other .dropbox {
  height: 180px;
  line-height: 1.5;
}
</style>